import time

from PyQt5.QtCore import QThread, pyqtSignal
from scapy.layers.inet import IP, TCP
from scapy.layers.l2 import Ether
from scapy.utils import rdpcap, PcapReader


class ReadPcapThread(QThread):
    update_text = pyqtSignal(str)  # pyqtSignal 是信号，用于在主线程中更新 UI 界面
    update_pcap_progressbar = pyqtSignal(int)  # 用于更新 PACP 文件加载进度条
    update_replay_progressbar = pyqtSignal(int)  # 用于更新回放进度条

    def __init__(self, file_path, replay_address='192.168.120.255'):
        super(ReadPcapThread, self).__init__()
        self.file_path = file_path
        self.replay_address = replay_address

    def run(self):
        packets = PcapReader(self.file_path)  # 使用 Scapy 库读取 pcap 文件
        # pcap_length = len(packets)
        start_time = packets[0].time  # 获取 pcap 文件开始时间
        for index, packet in enumerate(packets):
            print("read pacpFile!!!")
            delay = packet.time - start_time  # 计算当前包与开始包的时间差
            time.sleep(delay)  # 通过 sleep 函数模拟网络延迟
            packet[Ether].src, packet[Ether].dst = (
                packet[Ether].dst,
                packet[Ether].src,
            )  # 修改 MAC 地址
            packet[IP].src, packet[IP].dst = (
                self.replay_address,
                packet[IP].src,
            )  # 修改 IP 地址
            packet[TCP].seq, packet[TCP].ack = (
                packet[TCP].ack,
                packet[TCP].seq,
            )  # 修改 TCP 序列号和确认号
            self.update_text.emit(str(packet))  # 发射信号，在主线程中更新 UI 界面
            # replay_progress = int((index + 1) / pcap_length * 100)  # 计算回放进度
            # self.update_replay_progressbar.emit(replay_progress)  # 发射信号，更新回放进度条
        # self.update_pcap_progressbar.emit(100)  # 读取 PACP 文件完成后，更新 PACP 文件加载进度条


class NewReadPcapThread(QThread):
    signal_text = pyqtSignal(str)

    def __init__(self, file_path):
        super(NewReadPcapThread, self).__init__()
        self.file_path = file_path

    def run(self):
        print(self.file_path)
        packets = PcapReader(self.file_path)
        for index, packet in enumerate(packets):
            print(index, packet)
            self.signal_text.emit(str(packet))
